package org.jetnuke.modules.blog;

import org.apache.log4j.Logger;

import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.util.concurrent.Task;
import net.jforum.util.concurrent.executor.QueuedExecutor;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.BlogCategoryDAO;
import org.jetnuke.dao.BlogPostDAO;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogCategory;
import org.jetnuke.entities.BlogPost;
import org.jetnuke.entities.MainConfig;
import org.jetnuke.modules.blog.utils.BlogUtils;
import org.jetnuke.repository.MainConfigRepository;
import org.jetnuke.util.JetUtil;
import org.jetnuke.util.StringUtils;

public class SavePost implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SavePost.class);

	int id, category;
	String post_title, excerpt, content, save_continue, save, publish,
			post_status, trackback, comment_status = "closed",
			ping_status = "closed", post_password;

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		if (ui == null || ui.getID() < 2)
			return null;
		BlogPost bp = null;
		BlogPostDAO bpm = DataAccessDriver.getInst().newBlogPostDAO();
		if (id == 0) {
			bp = new BlogPost();
		} else {
			bp = bpm.retrieveByPK(id);
		}
		BlogCategoryDAO bcm = DataAccessDriver.getInst().newBlogCategoryDAO();
		List categories = bcm.selectByUser(ui.getID());
		Iterator catIterator = categories.iterator();
		boolean rightCat = false;
		while (catIterator.hasNext()) {
			BlogCategory cat = (BlogCategory) catIterator.next();
			if (cat.getID() == category) {
				rightCat = true;
				break;
			}
		}
		if (!rightCat) {
			category = ((BlogCategory) categories.get(0)).getID();
		}
		bp.setAID(ui.getID());
		bp.setCOMMENTSTATUS(comment_status);
		bp.setGUID(" ");
		bp.setPOSTCATEGORY(category);
		bp.setPOSTCONTENT(content);
		bp.setPOSTEXCERPT(excerpt);
		bp.setPOSTPASSWORD(post_password);
		bp.setPOSTDATE(new GregorianCalendar().getTime());
		if (publish != null)
			bp.setPOSTSTATUS("publish");
		else {
			if (id == 0 || (!"publish".equals(bp.getPOSTSTATUS()))) {
				bp.setPOSTSTATUS(post_status);
			}
		}
		bp.setPOSTTITLE(post_title);
		bp.setPINGSTATUS(ping_status);
		bp.setTOPING(trackback);
		if (id == 0) {
			bp.setPINGED("");

			id = bpm.addNew(bp);
			bp.setID(id);
			bp.setGUID(MainConfigRepository.getMainConfig().getNUKEURL()
					+ "do/blog/show_page?id=" + id);
			bpm.update(bp);

		} else {
			bpm.update(bp);
		}
		if (publish != null) {

			MainConfig config = (MainConfig) request
					.getAttribute("MAIN_CONFIG");
			final String url = config.getNUKEURL();
			QueuedExecutor.getInstance().execute(new Task() {

				public Object execute() throws Exception {
					if (logger.isDebugEnabled()) {
						logger.debug("$Task.execute() - start"); //$NON-NLS-1$
					}

					try {

						BlogUtils.doTrackback(url, id);
						BlogUtils.doPingback(url, id);
					} catch (Throwable e) {
						logger.error("$Task.execute()", e); //$NON-NLS-1$

						if (logger.isDebugEnabled()) {
							logger.debug("$Task.execute() - end"); //$NON-NLS-1$
						}
						return "FAILURE";
					}

					if (logger.isDebugEnabled()) {
						logger.debug("$Task.execute() - end"); //$NON-NLS-1$
					}
					return "SUCCESS";
				}
			});//
		}
		if (publish != null || save != null) {
			JetUtil.redirect(vc, response, request.getContextPath()
					+ "/do/blog/your_blog");

			if (logger.isDebugEnabled()) {
				logger
						.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
			}
			return null;
		}
		vc.put("post", bp);
		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

	public void setComment_status(String comment_status) {
		this.comment_status = comment_status;
	}

	public void setContent(String content) {
		if (logger.isDebugEnabled()) {
			logger.debug("setContent(String) - start"); //$NON-NLS-1$
		}

		this.content = StringUtils.filterText(content, false, true);

		if (logger.isDebugEnabled()) {
			logger.debug("setContent(String) - end"); //$NON-NLS-1$
		}
	}

	public void setExcerpt(String excerpt) {
		if (logger.isDebugEnabled()) {
			logger.debug("setExcerpt(String) - start"); //$NON-NLS-1$
		}

		this.excerpt = StringUtils.filterText(excerpt, false);

		if (logger.isDebugEnabled()) {
			logger.debug("setExcerpt(String) - end"); //$NON-NLS-1$
		}
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setPing_status(String ping_status) {
		this.ping_status = ping_status;
	}

	public void setPost_password(String post_password) {
		if (logger.isDebugEnabled()) {
			logger.debug("setPost_password(String) - start"); //$NON-NLS-1$
		}

		this.post_password = StringUtils.filterText(post_password, true);

		if (logger.isDebugEnabled()) {
			logger.debug("setPost_password(String) - end"); //$NON-NLS-1$
		}
	}

	public void setPost_status(String post_status) {
		this.post_status = post_status;
	}

	public void setPost_title(String post_title) {
		if (logger.isDebugEnabled()) {
			logger.debug("setPost_title(String) - start"); //$NON-NLS-1$
		}

		this.post_title = StringUtils.filterText(post_title, true);

		if (logger.isDebugEnabled()) {
			logger.debug("setPost_title(String) - end"); //$NON-NLS-1$
		}
	}

	public void setPublish(String publish) {
		this.publish = publish;
	}

	public void setSave(String save) {
		this.save = save;
	}

	public void setSave_continue(String save_continue) {
		this.save_continue = save_continue;
	}

	public void setTrackback(String trackback) {
		this.trackback = trackback;
	}

	public void setCategory(int category) {
		this.category = category;
	}

}
